package com.kuaimacode.kframework.agent.controller.sysparam;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.kuaimacode.kframework.agent.services.agent.SysAgentService;
import com.kuaimacode.kframework.agent.services.holiday.HolidayService;
import com.kuaimacode.kframework.agent.services.sysparam.SysParamService;
import com.kuaimacode.kframework.agent.services.weather.WeatherService;
import com.kuaimacode.kframework.agent.util.SessionUtil;
import com.kuaimacode.kframework.common.Constant;
import com.kuaimacode.kframework.common.JsonResult;
import com.kuaimacode.kframework.constants.PageConstants;
import com.kuaimacode.kframework.exception.ErrorEnum;
import com.kuaimacode.kframework.exception.ServerInternalErrorException;
import com.kuaimacode.kframework.mybatis.models.agent.SysAgent;
import com.kuaimacode.kframework.mybatis.models.agent.SysAgentWeather;
import com.kuaimacode.kframework.mybatis.models.category.AgentServ;
import com.kuaimacode.kframework.mybatis.models.holiday.Holiday;
import com.kuaimacode.kframework.mybatis.models.service.OneClass;
import com.kuaimacode.kframework.mybatis.models.sysparam.SysParam;
import com.kuaimacode.kframework.mybatis.models.sysparam.SysParamVo;
import com.kuaimacode.kframework.util.DateUtil;
import com.kuaimacode.kframework.util.DictUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import sun.util.resources.cldr.CalendarData;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author anzy
 * @date 2019/05/17
 */

/**
 * Controller
 */
@Controller
@RequestMapping({"/sysParam"})
public class SysParamController {
	private static String PAGE_FILE_NAME = "sysParam/";

	@Autowired
	private SysParamService sysParamServices;
    @Autowired
    private SysAgentService sysAgentService;
    @Autowired
    private HolidayService holidayService;

    @Autowired
    private WeatherService weatherService;
	/**
	 * 临时加价参数设置列表
	 * @param pageNum
	 * @param pageSize
	 * @param model
	 * @return
	 */
	@RequestMapping(value = {"/index"})
	public String index(@RequestParam(value = "pageNum", required = true, defaultValue = PageConstants.PAGE_NUM+"") int pageNum,
										@RequestParam(value = "pageSize", required = true, defaultValue = PageConstants.PAGE_SIZE+"") int pageSize,
						ModelMap model) {
		List<SysParam> list = sysParamServices.findAllFeeConfig();

        SysParamVo vo = new SysParamVo();
        for(SysParam sysParam :list){


            if(Constant.SYS_PARAM_FEE_NIGHT_SWITCH.equals(sysParam.getName())){
                SysAgent agent = sysAgentService.getAgentInfoById(SessionUtil.getAgentId());
                if(agent == null || agent.getStat() == Constant.AgentStatEnum.OFF.getCode()){
                    throw new ServerInternalErrorException(ErrorEnum.AGENT_NOT_NORMAL_OR_NOT_EXIST);
                }
                String nightS = "",nightE = "";
                BigDecimal reward = BigDecimal.ZERO;
                if(agent != null && agent.getStat() != Constant.AgentStatEnum.OFF.getCode()){
                    nightS = agent.getNightS();
                    nightE = agent.getNightE();
                    reward = agent.getAward();
                }

                //获取系统时间
                vo.setStartTime(nightS);
                vo.setEndTime(nightE);
                vo.setNightAward(reward);;
                if(Constant.SYS_PARAM_SWITCH_ON.equals(sysParam.getValue())){
                    vo.setType("1");
                }

            }else if(Constant.SYS_PARAM_FEE_WEATHER_SWITCH.equals(sysParam.getName())){

                List<SysAgentWeather> agentWeatherList = weatherService.getAgentWeather(SessionUtil.getAgentId());
                if(agentWeatherList != null && agentWeatherList.size() >0){
                    //同一分站，同一时间 只能设置一种特殊天气
                    //如果是特殊天气，记录费用及描述
                    SysAgentWeather sysAgentWeather = agentWeatherList.get(0);
                    vo.setWeatherAward(sysAgentWeather.getReward());
                }
                if(Constant.SYS_PARAM_SWITCH_ON.equals(sysParam.getValue())){
                    vo.setType("2");
                }

            }else if(Constant.SYS_PARAM_FEE_HOLIDAY_SWITCH.equals(sysParam.getName())){
                List<Holiday> holidays = holidayService.getAgentHoliday(SessionUtil.getAgentId(),DateUtil.format(new Date(),DateUtil.LONG_DATE_FORMAT),
                        DateUtil.format(new Date(),DateUtil.LONG_DATE_FORMAT));
                if(holidays!=null&&holidays.size()>0){
                    Holiday holiday = holidays.get(0);
                    vo.setHolidayAward(holiday.getReward());

                }
                if(Constant.SYS_PARAM_SWITCH_ON.equals(sysParam.getValue())){
                    vo.setType("3");
                }


            }

        }
        if(vo.getType()==null) vo.setType("1");


		model.put("sysParam", vo);
		return PAGE_FILE_NAME + "index";
	}


    @RequestMapping(value = {"/edit"}, method = RequestMethod.POST)
    @ResponseBody
    public JsonResult edit(SysParamVo vo, Boolean isAdd,ModelMap map) {
        try {
            if("1".equals(vo.getType())){
                //
                if(vo.getNightAward()==null) return JsonResult.failure("未设置深夜服务临时加价金额");
                if(vo.getStartTime()==null) return JsonResult.failure("未设置深夜服务开始时间");
                if(vo.getEndTime()==null) return JsonResult.failure("未设置深夜服务结束时间");

                SysAgent agent  = sysAgentService.getById(SessionUtil.getAgentId());
                agent.setAward(vo.getNightAward());
                agent.setNightE(vo.getEndTime());
                agent.setNightS(vo.getStartTime());
                sysAgentService.updateById(agent);
                //设置开关
                sysParamServices.offAllAndOpenSelf(Constant.SYS_PARAM_FEE_NIGHT_SWITCH);



            }else if ("2".equals(vo.getType())){
                //特殊天气
                if(vo.getWeatherAward()==null) return JsonResult.failure("未设置特殊天气临时加价金额");
                //先删除后增加
                QueryWrapper queryWrapper = new QueryWrapper();
                queryWrapper.eq("agent_id",SessionUtil.getAgentId());
                weatherService.remove(queryWrapper);

                SysAgentWeather weather = new SysAgentWeather();
                weather.setAgentId(SessionUtil.getAgentId());
                weather.setStatus(Constant.DeleteStateEnum.NORMAL.getCode().toString());
                weather.setStartTime(new Date());
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(new Date());
                calendar.set(Calendar.YEAR,2099);
                weather.setEndTime(calendar.getTime());
                weather.setReward(vo.getWeatherAward());
                weather.setCreateAt(new Date());
                weatherService.save(weather);

                sysParamServices.offAllAndOpenSelf(Constant.SYS_PARAM_FEE_WEATHER_SWITCH);

            }else if("3".equals(vo.getType())){
                //节假日
                if(vo.getHolidayAward()==null) return JsonResult.failure("未设置节假日临时加价金额");

                QueryWrapper queryWrapper = new QueryWrapper();
                queryWrapper.eq("agent_id",SessionUtil.getAgentId());
                holidayService.remove(queryWrapper);

                Holiday holiday = new Holiday();
                holiday.setAgentId(SessionUtil.getAgentId());
                holiday.setStatus(Constant.DeleteStateEnum.NORMAL.getCode());
                holiday.setBeginDate(new Date());
                holiday.setReward(vo.getHolidayAward());
                holiday.setEndDate(DateUtil.stringtoDate("9999-12-31",DateUtil.LONG_DATE_FORMAT));
                holiday.setCreateAt(new Date());

                holidayService.save(holiday);

                sysParamServices.offAllAndOpenSelf(Constant.SYS_PARAM_FEE_HOLIDAY_SWITCH);

            }
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.failure(e.getMessage());

        }
        return JsonResult.success();
    }



    @ResponseBody
    @PostMapping(value = "/off/{name}")
    public JsonResult off(@PathVariable String name, ModelMap map) {
        try {
            SysParam sysParam = sysParamServices.findByName(name, SessionUtil.getAgentId());
            sysParam.setValue(Constant.SYS_PARAM_SWITCH_OFF);
            sysParamServices.updateById(sysParam);
        } catch (Exception e) {
            return JsonResult.failure(e.getMessage());
        }
        return JsonResult.success();
    }

    @ResponseBody
    @PostMapping(value = "/on/{name}")
    public JsonResult on(@PathVariable String name, ModelMap map) {
        try {
            sysParamServices.offAllAndOpenSelf(name);
        } catch (Exception e) {
            return JsonResult.failure(e.getMessage());
        }
        return JsonResult.success();
    }


}
